package cn.bonoon.controllers.account;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.bonoon.core.plugins.AccountService;
import cn.bonoon.entities.plugins.AccountEntity;
import cn.bonoon.kernel.util.StringHelper;
import cn.bonoon.kernel.web.controllers.AbstractController;
import cn.bonoon.kernel.web.models.DialogModel;
import cn.bonoon.kernel.web.models.JsonResult;

@Controller
@RequestMapping("s/sys/account")
public class AccountResetpwdController extends AbstractController {

	@Value("${user.password.pattern}")
	private String pattern;
	@Value("${user.password.pattern.exception}")
	private String patternException;
	
	@Autowired
	private AccountService accountService;

	@RequestMapping(value = "!{mid}/resetpwd.do", method = { POST, GET })
	public ModelAndView get(HttpServletRequest request, @PathVariable("mid") String mid, Long id, String gridid) {
		DialogModel model = new DialogModel(mid, request);
		model.addForm(id);
		model.addObject("id", id);
		model.addObject("gridid", gridid);
		AccountEntity account = accountService.get(id);
		model.addObject("name", account.getName());
		model.addObject("loginName", account.getLoginName());
		model.addObject("pattern", pattern);
		model.addObject("patternException", patternException);
		return model.execute("sys/account/account-resetpwd");
	}

	private static final int PLOY_INPUT = 0;
	private static final int PLOY_RANDOM = 1;

	@ResponseBody
	@RequestMapping(value = "!{mid}/pwd!save.b", method = POST)
	public final JsonResult updatePwd(HttpServletRequest request, @PathVariable("mid") String mid, final Long id, int ploy, String pwd,
			String repwd, String email, String phone, Boolean enforce) {
		try {
			boolean f = null != enforce && enforce.booleanValue();
			String sendPwd = "";
			switch (ploy) {
			case PLOY_INPUT:
				sendPwd = accountService.resetPassword(id, pwd, repwd, f);
				break;
			case PLOY_RANDOM:
				sendPwd = accountService.randomPassword(id, f);
				break;
			default:
				throw new Exception("没有指定有效的密码生成策略！");
			}
			if (StringHelper.isNotEmpty(email)) {
				// 邮件通知
			}
			if (StringHelper.isNotEmpty(phone)) {
				// 手机通知
			}
			return JsonResult.result(sendPwd);
		} catch (Throwable t) {
			return JsonResult.error(t);
		}
	}

}
